<template>
  <!-- 修改用户对话框 -->
  <el-dialog v-model="visible" title="修改合同信息" width="800px">
    <el-form ref="contractUpdateRef" :model="contractUpdate" :rules="rules" label-position="top">
      <el-row>
        <el-col :span="10">
          <el-form-item label="合同名称：" prop="contractName">
            <el-input v-model="contractUpdate.contractName" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="工程名称：" prop="projectName">
            <el-input v-model="contractUpdate.projectName" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="工程地点：" prop="workRegion">
            <el-input v-model="contractUpdate.workRegion" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="签订甲方：" prop="otherCustomer">
            <el-input v-model="contractUpdate.otherCustomer" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="签订乙方：" prop="company">
            <el-input v-model="contractUpdate.company" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="签订地址：" prop="signingAddress">
            <el-input v-model="contractUpdate.signingAddress" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="签订日期：" prop="signingDate">
            <el-date-picker v-model="contractUpdate.signingDate" type="date" placeholder="选择日期" :size="size"
              format="YYYY/MM/DD" value-format="YYYY/MM/DD" disabled/>
          </el-form-item>

          <el-form-item label="合同工期">
            <el-date-picker v-model="contractUpdate.date" type="daterange" unlink-panels range-separator="To"
              start-placeholder="开始日期" end-placeholder="结束日期" size="large" disabled />
          </el-form-item>

        </el-col>
        <el-col :span="12" style="margin-left: 30px">
          <el-from-item label="施工类型:" prop="constructionTypeList">
            <span>施工类型</span>
            <el-select v-model="constructionTypeList" multiple placeholder="选择施工类型" style="width: 240px"
              @change="changeType" disabled >
              <el-option v-for="item in typeList" :key="item.id" :label="item.constructionType" :value="item.id" />
            </el-select>
          </el-from-item>

          <div v-for="(item, index) in selectedType">
            <el-col :span="10">
              <el-form-item :label="item.constructionType + ' 单位'">
                <el-input autocomplete="off" :placeholder="item.unitName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="10" style="margin-left: 10px">
              <el-form-item :label="item.constructionType + ' 单价(元)'">
                <el-input v-model="item.unitPrice" autocomplete="off" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item :label="item.constructionType + ' 数量'">
                <el-input v-model="item.number" autocomplete="off" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="10" style="margin-left: 10px">
              <el-form-item :label="item.constructionType + ' 金额'">
                <el-input autocomplete="off" :placeholder="item.number * item.unitPrice" disabled />
              </el-form-item>
            </el-col>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { put, tip, WAREHOUSE_CONTEXT_PATH, get } from "@/common";
import { Plus } from '@element-plus/icons-vue'

const visible = ref(false); // 该页面的可见性
// 修改合同对象
const contractUpdate = reactive({
  contractName: '',
  projectName: '',
  workRegion: '',
  otherCustomer: '',
  company: '',
  signingAddress: '',
  signingDate: '',
  date: []
});


// 该对话框打开并初始化
const open = (contract) => {
  console.log(contract)
  for (let prop in contract) {
    contractUpdate[prop] = contract[prop];
  }
  console.log(contractUpdate)
  contractUpdate.date[0] = contractUpdate["startTime"]
  contractUpdate.date[1] = contractUpdate["endTime"]
  constructionTypeList.value.length = 0;
  selectedType.value.length = 0;
  typeList.value.length = 0;
  get("/constructionType/constructionType-list").then(result1 => {
    typeList.value = result1.data;

    get('/contract/getConstructionTypeList/' + contract.contractId).then(result2 => {

      // selectedType.value = result2.data

      result2.data.forEach(item => {
        constructionTypeList.value.push(item.construction)
        item.constructionType = typeList.value.find(t => t.id == item.construction).constructionType
        item.unitName = typeList.value.find(t => t.id == item.construction).unitName
        selectedType.value.push(item)
      })
    })
  })




  visible.value = true;
};

// 获得所有类型
const typeList = ref([]);
const constructionTypeList = ref([]);
const getTypeList = () => {
  get("/constructionType/constructionType-list").then(result => {
    console.log(result.data)
    typeList.value = result.data;
    console.log(typeList)
  })
}

const contractUpdateRef = ref();
// 定义
const emit = defineEmits(["ok"]);
// 修改用户提交
const updateContract = () => {
  contractUpdateRef.value.validate(valid => {
    if (valid) {
      if (contractUpdate.customerId == -1) {
        contractUpdate.customerId = ''
      }
      contractAdd.value.startTime = formatDate(contractAdd.value.date[0])
      contractAdd.value.endTime = formatDate(contractAdd.value.date[1])
      contractAdd.value.contractEginnerList = contractEginnerList
      contractAdd.value.constructionTypeList = constructionTypeList;
      selectedType.value.forEach(element => {
        contractAdd.value.selectedType.push(
          {
            id: element.id,
            number: element.number,
            unitPrice: element.unitPrice
          })
      });
      console.log(contractAdd.value)
      delete contractAdd.value.date
      put('/contract/updateConstructionContract', contractUpdate).then(result => {
        emit('ok');
        tip.success(result.message);
        visible.value = false; // 关闭对话框
      });
    }
  });
}

// 日期格式化函数
function formatDate(dateStr) {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 获得所有产品
const productList = ref();
const getProductList = () => {
  get("/product-material/product-list").then(result => {
    productList.value = result.data;
  });
}
getProductList();


const selectedType = ref([]);
const daleteType = ref([]);
const addType = ref([]);
const changeType = () => {
  // selectedType.value.length = 0;
  // selectedType.value = []

  // constructionTypeList.value.forEach(i => {
  //   selectedType.value.push(typeList.value.find(t => t.id === i))
  // });
  console.log(constructionTypeList.value)
  const addedTypeIds = constructionTypeList.value.filter(id => !selectedType.value.some(type => type.id === id));
  const removedTypeIds = selectedType.value.map(type => type.id).filter(id => !constructionTypeList.value.includes(id));
  console.log(addedTypeIds)
  console.log(removedTypeIds)
  // 更新 selectedTypeList，新增类型
  addedTypeIds.forEach(id => {
    const newType = typeList.value.find(type => type.id === id);
    if (newType) {
      selectedType.value.push(newType);
    }
  });

  // 更新 selectedTypeList，删除类型
  removedTypeIds.forEach(id => {
    selectedType.value = selectedType.value.filter(type => type.id !== id);
  });

  // 打印更新后的 selectedTypeList 以供调试
  console.log(selectedType.value);
}


defineExpose({ open });
</script>
<style scoped>
.avatar-uploader,
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>